package org.rency.common.trigger.schedule;

import java.util.List;

import org.quartz.JobDetail;
import org.rency.common.trigger.factory.AbstractDaemonJob;
import org.rency.common.trigger.factory.DaemonJob;
import org.rency.common.trigger.util.DaemonTriggerConverter;
import org.rency.common.trigger.util.TriggerDict;
import org.rency.common.utils.domain.SpringContextHolder;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;

public class DaemonMethodInvokingJobDetailFactoryBean extends MethodInvokingJobDetailFactoryBean{

	public JobDetail getJobDetail() {
		return super.getObject();
	}

	public DaemonMethodInvokingJobDetailFactoryBean(DaemonTriggerBean jobBean) throws ClassNotFoundException, NoSuchMethodException {
		super.setTargetClass(DaemonJob.class);
		super.setArguments(new Object[]{DaemonTriggerConverter.convert2DaemonContext(jobBean)});
		super.setTargetMethod(TriggerDict.JOB_EXECUTE_METHOD);
		
		List<AbstractDaemonJob> jobList = SpringContextHolder.getBeans(AbstractDaemonJob.class);
		String targetJobName = jobBean.getBeanName().substring(0, 1).toUpperCase()+jobBean.getBeanName().substring(1, jobBean.getBeanName().length())+TriggerDict.JOB_BEAN_SUFFIX;
		AbstractDaemonJob targetJob = null;
		for(AbstractDaemonJob dj : jobList){
			String jobName = dj.getClass().getSimpleName();
			if( targetJobName.equals(jobName) ){
				targetJob = dj;
				break;
			}
		}
		if(targetJob == null){
			throw new ClassNotFoundException("未找到任务["+jobBean.getBeanName()+TriggerDict.JOB_BEAN_SUFFIX+"].");
		}
		super.setTargetClass(targetJob.getClass());
		super.setTargetObject(targetJob);
		super.setConcurrent(jobBean.getConcurrentTag());
		super.setBeanName(TriggerDict.DAEMON_TRIGGER_NAME+jobBean.getBeanName());
		super.afterPropertiesSet();
	}
	
}